from flask import Blueprint, request, jsonify
from datetime import datetime
from extensions import db
from models import Attendance
from sqlalchemy.exc import IntegrityError
from studata import all_stu_name



# 创建蓝图
submit_attendance_bp = Blueprint('submit_attendance', __name__)
# 定义路由
@submit_attendance_bp.route('/submit_attendance', methods=['POST'])
def submit_attendance():
    data = request.get_json()
    print(data)
    date_str = data.get('date')
    attendanceType = data.get('attendanceType')
    attendanceStatus = data.get('attendanceStatus')
    absentMembers = data.get('absentMembers', [])  # 默认为空列表
   
    if attendanceStatus == '缺勤':
        absentStudent_str =",".join(absentMembers)
    if attendanceStatus == '出勤':
        absent_stu_list=[x for x in all_stu_name if x not in absentMembers]
        # 将列表转换为字符串
        absentStudent_str = ",".join(absent_stu_list)
     
    # 初始化缺勤人员名单
    morning_absent = ""
    exercise_absent = ""
    school_over_absent = ""
    phone_absent = ""

    if attendanceType == '早点名':
        morning_absent = absentStudent_str
    if attendanceType == '课间操':
        exercise_absent = absentStudent_str
    if attendanceType == '放学点名':
        school_over_absent = absentStudent_str
    if attendanceType == '手机未交':
        phone_absent = absentStudent_str
  
    # 将日期字符串转换为 Python 的 date 对象
    try:
        date = datetime.strptime(date_str, '%Y-%m-%d').date()
    except ValueError:
        return jsonify({'message': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400

    try:
        # 创建新的考勤记录
        new_attendance = Attendance(
            date=date,
            morning_absent=morning_absent,
            exercise_absent=exercise_absent,
            school_over_absent=school_over_absent,
            phone_absent=phone_absent
        )
       
        # 保存到数据库
        add_attendance(new_attendance)
        # 返回成功响应
        # 构建返回数据
        response_data = {
            'message': '考勤数据提交成功',
            'data': {
                'date': date_str,
                'morning_absent': new_attendance.morning_absent,  # 直接使用字符串
                'exercise_absent': new_attendance.exercise_absent,  # 直接使用字符串
                'school_over_absent': new_attendance.school_over_absent,  # 直接使用字符串
                'phone_absent': new_attendance.phone_absent  # 直接使用字符串
            }
        }
        # 返回 JSON 响应
        return jsonify(response_data), 201

    except Exception as e:
        print(e)
        # 处理错误
        db.session.rollback()
        return jsonify({
            'message': '考勤数据提交失败',
            'error': str(e)
        }), 500




def add_attendance(new_attendance):
    """
    添加考勤记录。
    如果日期已存在，则将新数据追加到现有记录的相应字段中。
    如果日期不存在，则创建一条新记录。

    :param new_attendance: Attendance 类型的对象，包含新数据
    """
    try:
        # 检查数据库中是否已存在相同日期的记录
        existing_record = Attendance.query.filter_by(date=new_attendance.date).first()

        if existing_record:
            # 如果记录已存在，追加数据
            if new_attendance.morning_absent:
                if existing_record.morning_absent:
                    existing_record.morning_absent += f",{new_attendance.morning_absent}"
                else:
                    existing_record.morning_absent = new_attendance.morning_absent

            if new_attendance.exercise_absent:
                if existing_record.exercise_absent:
                    existing_record.exercise_absent += f",{new_attendance.exercise_absent}"
                else:
                    existing_record.exercise_absent = new_attendance.exercise_absent

            if new_attendance.school_over_absent:
                if existing_record.school_over_absent:
                    existing_record.school_over_absent += f",{new_attendance.school_over_absent}"
                else:
                    existing_record.school_over_absent = new_attendance.school_over_absent

            if new_attendance.phone_absent:
                if existing_record.phone_absent:
                    existing_record.phone_absent += f",{new_attendance.phone_absent}"
                else:
                    existing_record.phone_absent = new_attendance.phone_absent

            print(f"更新记录：{existing_record}")
        else:
            # 如果记录不存在，创建新记录
            db.session.add(new_attendance)
            print(f"添加新记录：{new_attendance}")

        # 提交更改到数据库
        db.session.commit()
        print("数据添加/更新成功！")
    except IntegrityError as e:
        # 处理数据库完整性错误（如唯一约束冲突）
        db.session.rollback()
        print(f"数据库错误：{e}")
    except Exception as e:
        # 处理其他异常
        db.session.rollback()
        print(f"出错信息：{e}")